package com.orhon.smartcampus.modules.user.fetcher;


import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.modules.base.entity.Schools;
import com.orhon.smartcampus.modules.base.gqlModel.GQLSchool;
import com.orhon.smartcampus.modules.base.mm.LangMapper;
import com.orhon.smartcampus.modules.base.mm.SchoolMapper;
import com.orhon.smartcampus.modules.student.dao.SInformationDao;
import com.orhon.smartcampus.modules.student.entity.SInformation;
import com.orhon.smartcampus.modules.teacher.dao.TInformationDao;
import com.orhon.smartcampus.modules.teacher.entity.TInformation;
import com.orhon.smartcampus.modules.user.dao.TokenService;
import com.orhon.smartcampus.modules.user.dao.UsersDao;
import com.orhon.smartcampus.modules.user.entity.Users;
import com.orhon.smartcampus.modules.user.gqlModel.GQLUser;
import com.orhon.smartcampus.modules.user.mm.UserMapper;
import com.orhon.smartcampus.utils.R;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * 通过用户名获取用户所有信息..
 */

@Component
public class ByUserNameFetcher implements DataFetcher {

    @Autowired
    UsersDao usersDao;

    @Autowired
    TInformationDao tInformationDao;

    @Autowired
    SInformationDao sInformationDao;

    @Autowired
    TokenService tokenService;

    @Override
    public Object get(DataFetchingEnvironment env) throws Exception {


        String username = env.getArgument("username");

        System.out.println(username);

        String chek_sql = "(username = '" + username +"' or mobile = '"+ username +"' or idcard = '" + username + "')";
        String hql = "from Users where deleted_at = null and " + chek_sql;

        Users item =  usersDao.findId(hql, null);
        if(item!=null) {
            GQLSchool gqlSchool = null;
            if (env.getSelectionSet().contains("school")){
                Schools schools = item.getSchool();
                gqlSchool = SchoolMapper.MAPPER.toSchool(schools);
            }
            GQLUser gqlUser = UserMapper.MAPPER.mapUser(item);
            gqlUser.setSchool(gqlSchool);
            //新加关联老师或者学生表查询名称
            String teacherSql = "from TInformation where userUsersByUserId = "+gqlUser.getId();
            TInformation tInformation =  tInformationDao.findId(teacherSql, null);
            if(tInformation!=null){
                gqlUser.setName(LangMapper.MAPPER.mapLang(tInformation.getTeacherName()));
            }
            String studentSql = "from SInformation where user = "+gqlUser.getId();
            SInformation sInformation =  sInformationDao.findId(studentSql, null);
            if(sInformation!=null){
                gqlUser.setName(LangMapper.MAPPER.mapLang(sInformation.getStudent_name()));
            }
            return gqlUser;
        }


        return null;
    }
}
